<template>
	<view>
		<view class="search_button" @click="searchBlueToothDevice">
				开始搜索蓝牙设备
			</view>
			<view class="search_button" @click="stopBlueToothDevice">
				停止搜索蓝牙设备
			</view>
			<scroll-view scroll-y class="box">
						<view class="item" v-for="item in deviceList">
							<view>
								<text>id: {{ item.deviceId }}</text>
							</view>
							<view>
								<text>name: {{ item.name }}</text>
							</view>
						</view>
					</scroll-view>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				deviceList:[]//设备列表,
			}
		},
		onLoad() {
			// this.initBlueTooth();
			this.createStateBuffer() ;
		},
		methods: {
			//初始化
			initBlueTooth (){
							 wx.authorize({
								scope: 'scope.bluetooth',
								success() {
								  // 用户已授权，可以调用蓝牙 API
								  console.log("用户已授权")
								  wx.openBluetoothAdapter({
										mode: "central", //开启主机
									 success(res) {
										console.log('蓝牙适配器打开成功', res);
									 },
									 fail(err) {
										console.error('蓝牙适配器打开失败', err);
									 }
								  });
								},
								fail(err) {
								  console.error('用户未授权蓝牙权限', err);
								  console.log("用户没授权")
								}
							 });
			},
			
		//搜索蓝牙
		 searchBlueToothDevice(){
			var that = this;
					 wx.startBluetoothDevicesDiscovery({
											success(res) {
												console.log(res)
												wx.showLoading({
													title:"正在搜索设备",
													duration:30000
												})
													wx.onBluetoothDeviceFound(function (device) {
																// 遍历搜索到的设备
																if (device.devices.length) {
																  device.devices.forEach((item) => {
																	 //搜到的每个设备
																	 if (
																		item.name?.includes("ZHJ1-")
																	 ) {
																		console.log("找到目标设备", item);
																		wx.hideLoading()
																		//取消扫描
																		wx.stopBluetoothDevicesDiscovery();
																		//4、连接目标蓝牙设备
																		that.createBLEConnection(item);
																	 }
																  });
																}
															 });
													},
											fail(res) {
												console.log(res);
												wx.showToast({
													title: `蓝牙设备服务发现设备${res.errMsg}`,
													icon: "none",
													duration: 3000,
												})
											}
						})
							 
			 },
			
		
			//连接蓝牙
			createBLEConnection(item) {
					var that = this;
					wx.createBLEConnection({
					  deviceId: item.deviceId,
					  success: function (res) {
						 console.log("连接BLE设备成功", res);
						 // 5、获取蓝牙设备可用服务
						 that.getBLEDeviceServices(item);
					  },
					  fail: function (err) {
						 console.error("连接BLE设备失败", err);
					  },
					});
				 },
			 //获取蓝牙服务
		  getBLEDeviceServices(item) {
				 var that = this;
				 wx.getBLEDeviceServices({
					deviceId: item.deviceId,
					success: (res) => {
					  console.log("获取BLE设备服务", res);
					  for (let i = 0; i < res.services.length; i++) {
						 if (
							res.services[i].isPrimary &&res.services[i].uuid === "0000180A-0000-1000-8000-00805F9B34FB"
						 ) {
							let deviceId = item.deviceId;
							let serviceId = res.services[i].uuid;
							//6、获取BLE设备特征值以及读写服务
							 this.getCharacteId(deviceId, serviceId);
						 }
					  }
					},
				 });
			  },
				  
		 
		 //获取设备特征值
			getCharacteId(deviceId,services){
			  wx.getBLEDeviceCharacteristics({
				 deviceId:deviceId,
				 serviceId:services,
				 success:(res)=>{
					console.log(res)
				
				 },
				 fail:(err)=>{
					console.log(err)
				 }
			  })
			},
			createStateBuffer() {
				  var addData = new Array();
				  let buffer = new ArrayBuffer(12);
				  let dataView = new DataView(buffer);
				  // 固定头
				  dataView.setUint8(0, 0XA5);
				  dataView.setUint8(1, 0x5A);
				  dataView.setUint8(2, 0x03);
				  dataView.setUint8(3, 0x07);
				  addData.push(0XA5)
				  addData.push(0x5A)
				  addData.push(0x03)
				  addData.push(0x07)
				  const now = new Date();
				  const year = now.getFullYear().toString().padStart(4, '0');
				  const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
				  const day = now.getDate().toString().padStart(2, '0');
				  const hours = now.getHours().toString().padStart(2, '0');
				  const minutes = now.getMinutes().toString().padStart(2, '0');
				  const seconds = now.getSeconds().toString().padStart(2, '0');
				  // 拼接成 YYYYMMDDHHMMSS 格式的字符串
				  const dateTimeString = year + month + day + hours + minutes + seconds;
					 console.log(dateTimeString)
				  for (let i = 0; i < dateTimeString.length; i += 2) {
					 const hex = '0x'+ parseInt(dateTimeString.substr(i, 2), 10).toString(16).padStart(2,'0');
					 dataView.setUint8(4+i/2,hex)
					 addData.push(parseInt(dateTimeString.substr(i, 2), 10))
					 console.log(hex)
				  }
				  let sum = 0;
				  addData.forEach(number =>{
					  sum += number
				  })
				  let checkBit = '0x'+ parseInt( ('0x'+ sum.toString(16) & 0xFF), 10).toString(16).padStart(2,'0');
				  
				  dataView.setUint8(11, checkBit);
				  console.log(addData)
				  
				  console.log(dataView)
			  
				  // return dataView.buffer
				},
		 formatDateToHex() {
			 console.log("进入生成")
			
		 
			 // 将每两位数字转换为16进制，并去掉中间的"-"和":"
			 let hexString = '';
			
			 console.log(hexString)
			 return hexString;
		},
			
	 // ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function (bit) {
						return ('00' + bit.toString(16)).slice(-2);
					}
				);
				return hexArr.join('');
			},
			
			// 将16进制的内容转成我们看得懂的字符串内容
			 hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr =
					trimedStr.substr(0, 2).toLowerCase() === '0x'
						? trimedStr.substr(2)
						: trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					alert('存在非法字符!');
					return '';
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join('');
			}
		}
	}
</script>

<style>

</style>
